<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { PlusOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import AddMenuModal from './AddMenuModal.vue';
  import { getMenuListReq, deleteMenuReq, exportMenuReq } from '/@/api/menu';
  import { useGlobSetting } from '/@/hooks/setting';
  import { MENU_TYPE_LIST } from './enum';
  import { getToken, getLoginApp } from '/@/utils/auth';
  import { Icon } from '/@/components/Icon';

  const { createMessage } = useMessage();
  const state = reactive({
    loading: false,
  });

  const loading = ref(false);

  const searchFormRef = ref();
  const searchForm = reactive({ menuName: '', createBy: '' });
  const searchFormActions = {
    search() {
      pgActions.reset();
      searchFormActions.onSearch();
    },
    async onSearch() {
      tableActions.getList();
    },
    reset(formRef) {
      formRef.resetFields();
      pgActions.reset();
      tableActions.getList();
    },
  };

  const table = reactive({
    data: [],
    selected: [] as any,
  });

  const token = getToken();
  const loginApp = getLoginApp();
  const headers = {
    Authorization: token,
    Clientid: loginApp.currentId,
  };
  const { apiUrl } = useGlobSetting();
  const tableActions = {
    selectionChange(v) {
      table.selected = v;
    },
    async getList() {
      let params = {
        menuName: searchForm.menuName,
        createBy: searchForm.createBy,
      };
      state.loading = true;
      let { data: ret, code, msg } = await getMenuListReq(params);
      state.loading = false;
      if (code === 200) {
        table.data = ret || [];
        table.selected = [];
      } else {
        createMessage({
          message: msg,
          type: 'error',
        });
      }
    },
    create() {
      modal.data = undefined;
      modalActions.show();
    },
    update(r) {
      modal.data = r;
      modalActions.show();
    },
    delete(r) {
      deleteReq([r.id]);
    },
    batchDel() {
      let ids = table.selected.map((e) => e.id);
      deleteReq([...ids]);
    },
    load() {
      loading.value = true;
    },
    import(res: any) {
      // console.log('res', res);
      loading.value = false;
      if (res.respCode == 200) {
        createMessage({
          message: '导入成功',
          type: 'success',
        });
        tableActions.getList();
      } else {
        createMessage({
          message: res.respMsg,
          type: 'error',
        });
        tableActions.getList();
      }
    },
    export() {
      const params = {
        menuName: searchForm.menuName,
        createBy: searchForm.createBy,
      };
      exportMenuReq(params);
      // .then((res) => {
      //   // 导出JSON文件
      //   const blob = new Blob([JSON.stringify(res)], {
      //     type: 'application/json;charset=utf-8',
      //   });
      //   const fileName = '菜单数据.json';
      //   if ('download' in document.createElement('a')) {
      //     // 非IE下载
      //     const elink = document.createElement('a');
      //     elink.download = fileName;
      //     elink.style.display = 'none';
      //     elink.href = URL.createObjectURL(blob);
      //     document.body.appendChild(elink);
      //     elink.click();
      //     URL.revokeObjectURL(elink.href); // 释放URL 对象
      //     document.body.removeChild(elink);
      //   } else {
      //     // IE10+下载
      //     navigator.msSaveBlob(blob, fileName);
      //   }
      //   // TODO 会同时出现一个错误无文字提示框
      //   createMessage({
      //     message: '导出成功',
      //     type: 'success',
      //   });
      // })
      // .catch((err) => {
      //   console.log(err);
      // });
    },
  };

  const pg = reactive({
    current: 1,
    size: 20,
    total: 0,
  });

  const pgActions = {
    reset: () => {
      pg.current = 1;
      pg.size = 20;
      pg.total = 0;
    },
    currentChange(r) {
      pg.current = r;
      searchFormActions.onSearch();
    },
    sizeChange(r) {
      pg.current = r;
      pg.size = r;
      searchFormActions.onSearch();
    },
  };

  const modal = reactive({
    visible: false,
    data: undefined,
  });

  const modalActions = {
    success() {
      pg.current = 1;
      searchFormActions.onSearch();
    },
    show() {
      modal.visible = true;
    },
  };
  // req
  async function deleteReq(p) {
    state.loading = true;
    const { code, msg } = await deleteMenuReq({ ids: p });
    state.loading = false;
    if (code == 200) {
      createMessage({
        message: msg,
      });
      searchFormActions.onSearch();
    }
  }

  searchFormActions.onSearch();
</script>

<template>
  <div class="p-4 menu-management">
    <div class="searchBox px-4 pt-4">
      <el-form label-width="70px" :model="searchForm" ref="searchFormRef" inline>
        <el-form-item prop="menuName" label="菜单名称">
          <el-input placeholder="请输入菜单名称" v-model="searchForm.menuName" clearable />
        </el-form-item>
        <el-form-item prop="createBy" label="创建人">
          <el-input placeholder="请输入创建人" v-model="searchForm.createBy" clearable />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" :loading="state.loading" @click="searchFormActions.search"
            >查询</el-button
          >
          <el-button @click="searchFormActions.reset(searchFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="middle-content p-4">
      <div class="tools mb-4">
        <div class="toolBtns">
          <el-button type="primary" @click="tableActions.create"> <PlusOutlined />新建 </el-button>
          <!-- <el-upload
            :disabled="loading"
            :action="`${apiUrl}/core/menu/importMenuExcel`"
            :on-progress="tableActions.load"
            :on-success="tableActions.import"
            :show-file-list="false"
            :headers="headers"
            :accept="'.xls,xlsx,.XLS,.XLSX'"
            style="display: inline-block; margin: 0 10px"
          >
            <el-button type="primary" :loading="loading">
              <ImportOutlined v-if="!loading" />
              导入
            </el-button>
          </el-upload>
          <el-button type="primary" @click="tableActions.export">
            <ExportOutlined />
            导出
          </el-button> -->
          <el-popconfirm
            title="确定要删除吗？"
            @confirm="tableActions.batchDel"
            confirm-button-text="确定"
            cancel-button-text="取消"
          >
            <template #reference>
              <el-button link :disabled="table.selected.length == 0">
                <Icon icon="ep:delete" />批量删除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <div class="selected">
          已选择<span class="blue">{{ table.selected.length }} 项</span>
        </div>
      </div>
      <el-table
        class="mb-4"
        v-loading="state.loading"
        :data="table.data"
        @selection-change="tableActions.selectionChange"
        row-key="id"
        :header-cell-style="{ background: '#f1f3f7' }"
      >
        <el-table-column type="selection" width="55" fixed />
        <el-table-column
          prop="menuName"
          label="菜单名称"
          :width="220"
          fixed
          show-overflow-tooltip
        />
        <el-table-column prop="menuUrl" label="菜单别名" :width="220" show-overflow-tooltip />
        <el-table-column prop="path" label="菜单url" :width="220" show-overflow-tooltip />
        <el-table-column prop="componentPath" label="组件url" :width="200" show-overflow-tooltip />
        <el-table-column prop="sort" label="菜单排序" :width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="菜单类型" :width="200" show-overflow-tooltip>
          <template #default="scope">
            {{ MENU_TYPE_LIST.filter((e) => e.value == scope.row.type)[0]?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="clientId" label="应用" :width="200">
          <template #default="scope">
            {{ scope.row.clientModel?.clientName }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" :width="120" />
        <el-table-column prop="remark" label="备注" :width="220" />
        <el-table-column prop="operation" label="操作" :width="220" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="tableActions.update(scope.row)">编辑 </el-button>
            <el-popconfirm
              title="确定要删除吗？"
              @confirm="tableActions.delete(scope.row)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        class="flex justify-end"
        background
        layout="total, sizes, prev, pager, next"
        :total="pg.total"
        :current-page="pg.current"
        v-model:page-size="pg.size"
        @current-change="pgActions.currentChange"
        :page-sizes="[20, 30, 50]"
      /> -->
    </div>
    <AddMenuModal
      v-model:visible="modal.visible"
      :data="modal.data"
      :menuList="table.data"
      @success="modalActions.success"
    />
  </div>
</template>

<style lang="less" scoped>
  html[data-theme='light'] {
    .searchBox,
    .middle-content {
      background-color: #fff;
    }
  }

  html[data-theme='dark'] {
    .searchBox,
    .middle-content {
      background-color: #151515;
    }
  }

  .menu-management {
    min-height: 100%;
    display: flex;
    flex-direction: column;

    .middle-content {
      flex: 1;

      .tools {
        display: flex;
        justify-content: space-between;
        .toolBtns {
          button {
            float: left;
          }
          div {
            float: left;
          }
        }
        .selected {
          line-height: 32px;
          .blue {
            margin-left: 5px;
            color: #237ae4;
          }
        }
      }
    }
  }
</style>
